/*Client.java Defines a client on the server.
Copyright (C) 2013  Dmytro Kostiantynovskyi, HartLi

This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License along
with this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.*/
import java.io.IOException;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import com.maxmind.geoip.LookupService;


public class Client {
	
	public String getClientIP() throws UnknownHostException, IOException{
		Console cons = new Console();
		String ip = "";
		try {
			ArrayList<String> lst = cons.ioConsole("host");
			ip = lst.get(lst.size()-2);
			Pattern p = Pattern.compile("(.*)(\\[\\d*\\])(.*)(:\\d*)");
			Matcher m = p.matcher(ip);
			if(m.find()){
				ip = m.group(3);
			}
			else
				ip = "";
		} catch (IOException e) {
			e.printStackTrace();
		}
		
		return ip;
	}
	
	public static String getLocation(String ip) throws IOException{
		String country = "";
		try {
	
		    // Uncomment for windows
		    String dbfile = Config.currentDirectory+Config.sep+Config.relativeInstallPath + Config.geoMapFile; 
		    // You should only call LookupService once, especially if you use
		    // GEOIP_MEMORY_CACHE mode, since the LookupService constructor takes up
		    // resources to load the GeoIP.dat file into memory
		    //LookupService cl = new LookupService(dbfile,LookupService.GEOIP_STANDARD);
		    LookupService cl = new LookupService(dbfile,LookupService.GEOIP_MEMORY_CACHE);
	
		    country = cl.getCountry(ip).getName();
		    cl.close();
		}
		catch (IOException e) {
		    System.out.println("IO Exception");
		}
		return country;
	}
}
